package com.example.file.controller;

import com.example.file.model.LoginBody;
import com.example.file.response.Response;
import com.example.file.service.LoginService;
import com.example.file.utils.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import static com.example.file.response.ResultEnum.ALLOW_ONLY_LOCAL_HOST;

@RestController
public class SysLoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public Response<String> login(@Validated @RequestBody LoginBody loginBody) {
        // 生成令牌
        String token = loginService.login(loginBody);
        return Response.success(token, "");
    }

    @PostMapping("/registUser")
    public Response<?> registUser(@Validated @RequestBody LoginBody loginBody, ServerHttpRequest serverHttpRequest) throws IOException {
        String ipAddr = IPUtils.getIpAddr(serverHttpRequest);
        boolean localIp = isLocalIp(ipAddr);
        if (!localIp) {
            return Response.fail(ALLOW_ONLY_LOCAL_HOST);
        }
        loginService.registUser(loginBody);
        return Response.success();
    }

    @PostMapping("/validUserExist")
    public Response<?> validUserExist() {
        loginService.validUserExist();
        return Response.success();
    }

    // 检查请求的 IP 地址是否是本机 IP 地址
    private boolean isLocalIp(String ip) throws IOException {
        // 获取所有本机的 IP 地址
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                // 判断该地址是否是本机地址，忽略回环地址（127.0.0.1）
                if (inetAddress.isSiteLocalAddress() && !inetAddress.isLoopbackAddress()) {
                    if (ip.equals(inetAddress.getHostAddress())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
